# _*_ coding: utf-8 _*_

import datetime
import time
import random
import pyautogui
import ctypes
import threading
from pynput.mouse import Listener as mListener
from pynput.keyboard import Key, Controller, Listener as kListener

pyautogui.FAILSAFE = False

POS_X = 406
POS_Y = 1059


class KeepOnline():
    def __init__(self):
        # self._stop = None\
        pass

    # 工作的时间范围设置
    def is_worktime(self):
        now = datetime.datetime.now()

        # 获取当前星期几（0 表示周一，6 表示周日）
        weekday = now.weekday()
        if 0 <= weekday <= 4:  # 周一到周五
            if datetime.time(8, 30) <= now.time() <= datetime.time(19):  # 8:30~19:00
                return True
            else:
                return False
        else:
            return False

    def check_pos(self):
        # 检测企微的鼠标位置, 获取到坐标值后设置参数
        try:
            while True:
                x, y = pyautogui.position()  # 获取当前鼠标位置
                print(f"Mouse position: X={x}, Y={y}")
                time.sleep(1)

        except KeyboardInterrupt:
            print("Program terminated.")

    def click_it(self):
        # 点击任务栏图标
        pyautogui.moveTo(POS_X, POS_Y)
        pyautogui.click()
        time.sleep(2)
        pyautogui.moveTo(POS_X, POS_Y)  # 防止意外挪动
        pyautogui.click()

    def running(self, ev_stop):
        while not ev_stop.is_set():
            ok = self.is_worktime()
            if ok:
                sleep_sec = random.randint(10, 30)  # 随机10~30秒
                print("{} sleep {} sec, then clickit".format(datetime.datetime.now(), sleep_sec))
                time.sleep(sleep_sec)

                pyautogui.FAILSAFE = False
                self.click_it()
            else:
                print("{} not work time".format(datetime.datetime.now()))
                time.sleep(600)  # 防止判断失效导致死循环


## Note
# 1. 确认：
#   确认电源设置不锁屏
#   确认程序工作时间范围
#   检测任务栏图标所在坐标， 并确认正确设置
# 2. 运行程序， 之后不要点击鼠标
# 3. 关闭显示器（不是锁屏）


def t_running(ev_stop):
    ko = KeepOnline()
    ko.running(ev_stop)


def on_key_press(key):
    try:
        print(f'键盘按下键：{key.char}')
    except AttributeError:
        print(f'键盘按下特殊键：{key}')
    if key == Key.enter:
        print("enter被按下，键盘监控退出")

        pyautogui.moveTo(10, 10)
        pyautogui.click()

        return False


def on_key_release(key):
    return True


def on_clicks(x, y, button, pressed):
    if pressed:
        print('on_click {} 鼠标点击事件被触发 {} {} {}'.format(datetime.datetime.now(), x, y, button))
        if x != POS_X or y != POS_Y:
            print("鼠标监控退出")

            keyboard = Controller()
            keyboard.press(Key.enter)
            keyboard.release(Key.enter)

            return False
        else:
            return True
    else:
        # 鼠标抬起事件
        print("on_click up")


if __name__ == "__main__":
    # ko = KeepOnline()
    # ko.check_pos()

    ev_stop = threading.Event()
    thread = threading.Thread(target=t_running, args=(ev_stop,))
    thread.start()
    time.sleep(10)  # N秒后不准操作鼠标和enter

    ml = mListener(on_click=on_clicks)
    kl = kListener(on_press=on_key_press, on_release=on_key_release)

    ml.start()
    kl.start()

    # ml.join()
    kl.join()

    ev_stop.set()
    print("lock screen")
    ctypes.windll.user32.LockWorkStation()

    thread.join()
    print("exited")
